<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .div1{
            width: 500px;
            height: 400px;
            position: relative;
        }
        .div2{
            width:50px;
            height:50px;
          
            position:absolute;
        }
    </style>
</head>
<body>
  <div class="div1">
    <div class="div2">aaaa</div>
</div>
<script>
    //获取操作对象
    var div1=document.querySelector('.div1')
    var div2=document.querySelector('.div2')
    //给按钮绑定点击事件
    var dsq;
    dsq=setInterval(function(){
                //获取小盒子移动的范围
                var a=div1.clientWidth-div2.offsetWidth
                var b=div1.clientHeight-div2.offsetHeight
                var c=minY=0
                //获取小盒子当前位置
                var x1=div2.offsetLeft
                var y1=div2.offsetTop
                //判断当前位置是否满足移动条件
                //从左往右
                if(y1==0 && x1<a){
                    div2.style.left=parseInt(x1)+5+'px'
                //从上往下
                }else if(y1<b && x1==a){
                    div2.style.top=parseInt(y1)+5+'px'
                //从右往左
                }else if(y1==b && x1>c){
                    div2.style.left=parseInt(x1)-5+'px'
                //从下往上
                }else if(x1==c && y1>minY){
                    div2.style.top=parseInt(y1)-5+'px'
                }
      },20)
</script>
</body>
</html>